//
//  ZYCManageTourRecordListViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/26.
//

#import "ZYCManageTourRecordListViewController.h"
#import "ZYCTourRecordsListCell.h"
#import "ZYCManageTourRecordMarkViewController.h"
#import "ZYCManageTourRecordDiscordViewController.h"
#import "ZYCMenuSliderView.h"
#import "ZYCTourRecordMenuView.h"
#import "ZYCTourRecordStatusPickerView.h"
#import "ZYCSelectPastDateView.h"
#import "ZYCTourRecordStatusModel.h"
#import "ZYCTourRecordsModel.h"
#import "ZYCNoDataView.h"
#import "ZYCLectureRecordHeaderView.h"
#import "UIView+Gt.h"

static NSInteger pageSize = 10;
@interface ZYCManageTourRecordListViewController ()<UITableViewDelegate,UITableViewDataSource,ZYCTourRecordMenuViewDelegate,ZYCTourRecordsListCellDelegate,ZYCLectureRecordHeaderViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) ZYCTourRecordMenuView *menuView;
@property (nonatomic, strong) ZYCTourRecordStatusPickerView *pickerView;
@property (nonatomic, strong) ZYCSelectPastDateView *dateSelectView;
@property (nonatomic, strong) ZYCLectureRecordHeaderView *headerView;

@property (nonatomic, strong) NSMutableArray *titles;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, copy) NSString *courseTime;
@property (nonatomic, copy) NSString *scope;
@property (nonatomic, copy) NSString *classStatus;
@property (nonatomic, copy) NSString *isObjection;//是否有异议（0：无，1：有）

@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) ZYCNoDataView *noDataView;

@end

@implementation ZYCManageTourRecordListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.type == ZYCElectiveLevelTypePrimary) {
        self.title = @"小学部";
        self.scope = @"0";
    }else{
        self.title = @"中学部";
        self.scope = @"1";
    }

    self.menuView.leftStr = [self.dateFormatter stringFromDate:[NSDate date]];
    
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.tableView];


}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.courseTime = [self getCurrentTime];
    [self loadNewData];
}
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}


- (void)loadNewData{
    self.pageNum = 1;
    NSDictionary *params = @{
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum),
        @"courseTime":self.courseTime ? self.courseTime : @"",
        @"scope":self.scope,
        @"classStatus":self.classStatus ? self.classStatus : @"",
        @"isObjection":self.isObjection ? self.isObjection : @""
    };
    
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TourRecord requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            [self.dataSource removeAllObjects];
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTourRecordsModel class] json:responseObject[@"body"][@"list"]];
            ZYCTourRecordsModel *first = array.firstObject;
            if (([first.dissentCount integerValue] != 0)) {// 是否有异常的
                self.tableView.tableHeaderView = self.headerView;
                NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
                NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@条数据有异议",first.dissentCount] attributes:attribtDic];
                [self.headerView.titleButton setAttributedTitle:attribtStr forState:UIControlStateNormal];
            }else{
                self.tableView.tableHeaderView = nil;
            }
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:array];
            [self.tableView reloadData];
            [self reset];
            [self.tableView.mj_header endRefreshing];
            if (self.dataSource.count == 0) {
                self.noDataView.hidden = NO;
                self.tableView.hidden = YES;
            }else{
                self.noDataView.hidden = YES;
                self.tableView.hidden = NO;
            }
        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}


-(void)loadMoreData{
    self.pageNum ++;
    NSDictionary *params = @{
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum),
        @"courseTime":self.courseTime ? self.courseTime : @"",
        @"scope":self.scope,
        @"classStatus":self.classStatus ? self.classStatus : @"",
        @"isObjection":self.isObjection ? self.isObjection : @""
    };
    
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TourRecord requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTourRecordsModel class] json:responseObject[@"body"][@"list"]];
            if (array.count == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.dataSource addObjectsFromArray:array];
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            }
        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)reset{
    [self.tableView.mj_footer setRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_footer resetNoMoreData];
}

// 加载有异议的数据
- (void)loadObjectionData{
    self.pageNum = 1;
    NSDictionary *params = @{
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum),
        @"courseTime":self.courseTime ? self.courseTime : @"",
        @"scope":self.scope,
        @"classStatus":self.classStatus ? self.classStatus : @"",
        @"isObjection":self.isObjection ? self.isObjection : @""
    };
    
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TourRecord requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            // 刷新完 重置
            self.isObjection = @"";
            [self.dataSource removeAllObjects];
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTourRecordsModel class] json:responseObject[@"body"][@"list"]];
            ZYCTourRecordsModel *first = array.firstObject;
            if (!([first.dissentCount boolValue] == 0)) {// 是否有异常的
                self.tableView.tableHeaderView = self.headerView;
                NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
                NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@条数据有异议",first.dissentCount] attributes:attribtDic];
                [self.headerView.titleButton setAttributedTitle:attribtStr forState:UIControlStateNormal];
            }else{
                self.tableView.tableHeaderView = nil;
            }
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:array];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            if (self.dataSource.count == 0) {
                self.noDataView.hidden = NO;
                self.tableView.hidden = YES;
            }else{
                self.noDataView.hidden = YES;
                self.tableView.hidden = NO;
            }
        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}



#pragma mark - ZYCTourRecordMenuViewDelegate

- (void)tourRecordMenuViewClickLeft{
    [self.dateSelectView show];
}
- (void)tourRecordMenuViewClickRight{
    [self.pickerView show];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCTourRecordsListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTourRecordsListCell class]) forIndexPath:indexPath];
    [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.section];
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 132.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ZYCTourRecordsModel *model = self.dataSource[indexPath.section];
    NSInteger status = [model.classStatus integerValue];
    if ([model.isObjection boolValue]) {
        ZYCManageTourRecordDiscordViewController *vc = [ZYCManageTourRecordDiscordViewController new];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (status == 0) {//标记
        ZYCManageTourRecordMarkViewController *vc = [ZYCManageTourRecordMarkViewController new];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }

}


#pragma mark - ZYCLectureRecordHeaderView
- (void)lectureRecordHeaderViewDidExpect{
    self.isObjection = @"1";
    [self loadObjectionData];
}


#pragma mark - getters
- (ZYCLectureRecordHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCLectureRecordHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 45.0f)];
        _headerView.delegate = self;
    }
    return _headerView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.menuView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.menuView.frame)) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCTourRecordsListCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTourRecordsListCell class])];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _tableView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (ZYCTourRecordMenuView *)menuView {
    if (!_menuView) {
        _menuView = [[ZYCTourRecordMenuView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 46.0f)];
        _menuView.leftStr = @"日期";
        _menuView.rightStr = @"全部";
        _menuView.delegate = self;
    }
    return _menuView;
}

- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}

- (ZYCTourRecordStatusPickerView *)pickerView{
    ZYCWeakSelf
    if (!_pickerView) {
        _pickerView = [[ZYCTourRecordStatusPickerView alloc] init];
        _pickerView.tipString = @"请选择状态";
        _pickerView.titles = self.titles;
        _pickerView.selectStatusBlock = ^(ZYCTourRecordStatusModel * _Nonnull model) {
            weakSelf.menuView.rightStr = model.title;
            weakSelf.classStatus = model.status;
            [weakSelf loadNewData];
        };

        [self.view addSubview:_pickerView];
    }
    return _pickerView;
}

- (ZYCSelectPastDateView *)dateSelectView {
    ZYCWeakSelf
    if (!_dateSelectView) {
        _dateSelectView = [[ZYCSelectPastDateView alloc] init];
        _dateSelectView.tipString = @"请选择时间";
        _dateSelectView.currentDate = [NSDate date];
        _dateSelectView.confirmAction = ^(NSString * _Nonnull dateStr) {
            weakSelf.courseTime = dateStr;
            weakSelf.menuView.leftStr = dateStr;
            [weakSelf loadNewData];
        };
        [self.view addSubview:_dateSelectView];
    }
    return _dateSelectView;
}

//巡堂状态（1：正常；2：迟到；3：取消；4：异常，5：标记）
- (NSMutableArray *)titles {
    if (!_titles) {
        _titles = [NSMutableArray array];
        {
            ZYCTourRecordStatusModel *model = [ZYCTourRecordStatusModel new];
            model.title = @"全部";
            model.status = @"";
            model.textColor = HEX_RGB(@"#39A85B");
            [_titles addObject:model];
        }
        
        {
            ZYCTourRecordStatusModel *model = [ZYCTourRecordStatusModel new];
            model.title = @"正常";
            model.status = @"1";
            model.textColor = HEX_RGB(@"#39A85B");
            [_titles addObject:model];
        }
        
        {
            ZYCTourRecordStatusModel *model = [ZYCTourRecordStatusModel new];
            model.title = @"迟到";
            model.status = @"2";
            model.textColor = HEX_RGB(@"E93C06");
            [_titles addObject:model];
        }
        
        {
            ZYCTourRecordStatusModel *model = [ZYCTourRecordStatusModel new];
            model.title = @"取消";
            model.status = @"3";
            model.textColor = HEX_RGB(@"#EB9F28");
            [_titles addObject:model];
        }
        {
            ZYCTourRecordStatusModel *model = [ZYCTourRecordStatusModel new];
            model.title = @"异常";
            model.status = @"4";
            model.textColor = HEX_RGB(@"#EB9F28");
            [_titles addObject:model];
        }
        {
            ZYCTourRecordStatusModel *model = [ZYCTourRecordStatusModel new];
            model.title = @"标记";
            model.status = @"5";
            model.textColor = HEX_RGB(@"#EB9F28");
            [_titles addObject:model];
        }

    }
    return _titles;
}


- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
